import React, {Component} from 'react';
import $ from 'jquery';
import * as tools from '../../../tools/tools';
import WrapRoleAddForm from '../RoleAdd/RoleAdd';
import WrappedSearchForm from '../../../components/SearchPanel/SearchPanel';
import { message, Form, Row, Col, Input, Button, Icon, Table, Modal, Tooltip, Cascader, Select, Checkbox } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;

const columns = [
    {
    title: '角色名',
    dataIndex: 'name',
  }, {
    title: '角色描述',
    dataIndex: 'remark',
  }, {
    title: '角色数量',
    dataIndex: 'count',
  },{
    title: '状态',
    dataIndex: 'status',
  }]; 

class RoleManagementIndex extends Component {
    constructor(props) {
        super(props);
    }
    state = {
        cRowKey : [],
        cRow : '',
        paginationC : {},
        cTabContent : [],
        modalTitle : '添加',
        visible : false,
        oldData : {},
        searchKeys : [
            {
                id : 'name',
                name : '角色',
                type : 1,
            },
            {
                id : 'status',
                name : '状态',
                type : 2,//input date
                options : [
                    {
                        val : 1,
                        text : '启用'
                    },{
                        val : -1,
                        text : '禁用'
                    }
                ]
            },
            {
                id : 'time',
                name : '创建时间',
                type : 3
            }
        ]
    }

    //处理分页数据
    handlePage  = (page, pageSize) => {
        this.getRoleInfo(page).then(tabcontent => {
            this.setState({
                cTabContent : tabcontent,
            });
        });
    }

    //获取表格内容
    getRoleInfo = (page=1) => {
        var that = this;
        return new Promise(resolve => {
            $.ajax({
                url : tools.apiUrl + 'manage/role_list',
                data : {
                    page,
                    token : localStorage.token
                },
                type : 'post',
                success : function(res) {
                    if(res.status == 1) {
                        resolve(that.formatData(res.result))
                    }
                }
            })
        })
    }
    showModal = () => {
        this.getNodes().then(res => {
            this.setState({
                treeData : res.result,
                visible : true,
                oldData : {},
                isModify : 0
            })
        });
    }
    modifyModal = () => {
        var that = this;
        if(this.state.cRowKey.length > 0) {
            var p1 = this.getNodes();
            var p2 = new Promise(resolve => {
                $.ajax({
                    url : tools.apiUrl + 'manage/role_info',
                    data : {
                        token : localStorage.token,
                        id : this.state.cRowKey[0]
                    },
                    type : 'post',
                    success : function(res) {
                        if(res.status == 1) {
                            var cRightIds = [];
                            var jsonStr = [];
                            res.result.pivot.forEach(val => {
                                console.log('val', val)
                                if(val.check_status == 1) {
                                    cRightIds.push(val.node_id + '')
                                }
                                jsonStr.push(JSON.stringify(val))
                            });
                            var oldData = {};
                            console.log(cRightIds)
                            oldData.oldIds = cRightIds.reverse();
                            oldData.id = res.result.id;
                            oldData.name = res.result.name;
                            oldData.remark = res.result.remark;
                            oldData.pivot = jsonStr;
                            resolve(oldData)
                        } 
                    }
                })
            })
            
            Promise.all([p1, p2]).then(function(res) {
                that.setState({
                    treeData : res[0].result,
                    visible : true,
                    oldData : res[1],
                    isModify : 1
                })
            })
           
        }
       
    }

    formatData = (res) => {
        var that = this;
        //处理分页
        console.log(res)
        this.setState({
            paginationC : {
                current : res.current_page,
                total : res.total,
                onChange : that.handlePage,
                pageSize : res.per_page
            }
        })
        //处理表格数据
        return res.data.map(val => {
            return {
                key : val.id,
                name : val.name,
                remark : val.remark,
                count : val.user.length,
                status : (val.status == 1 ? '启用' : '禁用'),
            }
        })
    }

    onCancel = () => {
        this.setState({
            visible : false,
            oldData : {},
            treeData : {}
        })
    }

    //获取所有角色的权限节点
    getNodes = () => {
        return new Promise(resolve => {
            $.ajax({
                url : tools.apiUrl + 'manage/jurisdiction_list',
                data : {
                    token : localStorage.token
                },
                type: 'post',
                success: function(res) {
                    if(res.status == 1) {
                        resolve(res);
                    }
                }
            })
        })
    }
    removeCount = () => {
        if(this.state.cRowKey.length > 0) {
            $.ajax({
                url : tools.apiUrl + 'manage/deladmin',
                data : {
                    token : localStorage.token,
                    id : this.state.cRowKey[0]
                },
                type : 'post',
                success : function(res) {
                    if(res.status == 1) {
                        this.handlePage();
                    }
                }
            })
        }
    }
    componentWillMount = () => {
        this.handlePage();
        var nodes = this.getNodes();
        Promise.all([nodes]).then(res => {
            var searchKeys = this.state.searchKeys;
            var nodes = res[0].result;
            this.setState({
                treeData : nodes,
                searchKeys : searchKeys
            })
        })
    }

    //获取全部可选择角色
    getRoles = () => {
        return new Promise(resolve => {
            $.ajax({
                url : tools.apiUrl + 'manage/all_role',
                type : 'post',
                data : {
                    token : localStorage.token,
                },
                success : function(res) {
                    if(res.status == 1) {
                        resolve(res.result)
                    }
                }
            })
        })
    }

    inactiveCount = () => {
        var that = this;
        if(this.state.cRowKey.length > 0) {
            $.ajax({
                url : tools.apiUrl + 'manage/statusrole',
                data : {
                    token : localStorage.token,
                    id : this.state.cRowKey[0],
                    status : -1
                },
                type : 'post',
                success : function(res) {
                    if(res.status == 1) {
                        that.handlePage();
                    }
                }
            })
        }
    }

    activeCount = () => {
        var that = this;
        console.log('1213', this.state.cRowKey)
        if(this.state.cRowKey.length > 0) {
            $.ajax({
                url : tools.apiUrl + 'manage/statusrole',
                data : {
                    token : localStorage.token,
                    id : this.state.cRowKey[0],
                    status : 1
                },
                type : 'post',
                success : function(res) {
                    if(res.status == 1) {
                        that.handlePage();
                    }
                }
            })
        }
    }

    onSearchCb = (data) => {
        var that = this;
        console.log('search', data);
        data.token = localStorage.token;
        if(data.time && data.time.length > 0) {
            data.created_start_time = data.time[0]._d.toLocaleDateString();
            data.created_end_time = data.time[1]._d.toLocaleDateString();
            data.time = '';
        }
        $.ajax({
            url : tools.apiUrl + 'manage/role_list',
            data,
            type:'post',
            success : function(res) {
                if(res.status == 1) {
                    that.setState({
                        cTabContent : that.formatData(res.result)
                    })
                }else {
                    that.setState({
                        cTabContent : []
                    })
                }
                
            }
        })
    }

    render() {
        var oldData = {}; 
        //判断是否有选择
        {this.state.isModify == 1 ? oldData=this.state.backShowInfo : { }};
        //模态框控制
        const modalStyle = {
            title : this.state.modalTitle,
            className : 'normal-modal-control',
            visible : this.state.visible,
        }
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                console.log(selectedRows, selectedRowKeys)
                this.setState({
                    cRow : selectedRows,
                    cRowKey : selectedRowKeys
                })
            },
            type: 'radio',//单选,
            selectedRowKeys : this.state.cRowKey,
        };

        return(
            <div>
                <div className="search-top">
                    <WrappedSearchForm 
                        searchKeys={this.state.searchKeys}
                        onSearchCb ={this.onSearchCb }
                    />
                </div>
                <div className="search-content">
                    <div className="city-biaotou">
                        <div className="city-biaotou-left">
                            <Button key="btn2" onClick={this.showModal} id="add_count">添加角色</Button> 
                            <Button key="btn3" onClick={this.modifyModal} id="modify_count">修改</Button>
                            <Button key="btn4" onClick={this.inactiveCount} >停用</Button> 
                            <Button key="btn5" onClick={this.activeCount}>启用</Button>
                            {/* <Button key="btn6" onClick={this.removeCount}>删除</Button> */}
                        </div>
                    </div>
                    <div className="search-result-box">
                        <Table 
                            rowSelection={rowSelection}
                            columns={columns}
                            dataSource={this.state.cTabContent}
                            pagination={this.state.paginationC}
                        />
                    </div>
                    <WrapRoleAddForm
                         modalStyle={modalStyle}
                         onCancel={this.onCancel}
                         treeData={this.state.treeData}
                         upDate={this.handlePage}
                         oldData={this.state.oldData}
                         isModify={this.state.isModify}
                    />
                </div>
            </div>
        )
    }
}
export default RoleManagementIndex



